<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addDialogVisible =true">添加角色</el-button>
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bb',{bt:i1===0}]"
            >
              <!-- 一级权限 -->
              <el-col :span="4">
                <el-tag closable @close="delRoleRights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二、三级权限 -->
              <el-col :span="20">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2===0?'':'bt']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delRoleRights(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="delRoleRights(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row.children}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="searchRole(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="success"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="allotRoleRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加 角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <el-form :model="addRuleForm" :rules="addRules" ref="addRuleFormRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog title="修改角色" :visible.sync="setDialogVisible" width="50%" @close="setDialogClose">
      <el-form :model="setRuleForm" :rules="addRules" ref="setRuleFormRef" label-width="90px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="setRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="setRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="allotDialogVisible" width="50%" @close="allotClose">
      <!--
            data  数据源
            label 绑定的属性 {}
            {
              label：看见的属性
              children：嵌套的子节点的属性
            }
            show-checkbox  是否显示复选框
            default-expand-all  是否默认展开所有节点

            node-key  选中之后获取的id

            default-checked-keys 默认选中的id数组

            default-expanded-keys 默认展开的id数组

            getCheckedKeys   方法获取所有全选key的数组

            getHalfCheckedKeys  方法获取所有半选状态key的数组
      -->
      <el-tree
        :data="rightsList"
        :props="allotProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
        ref="allotTreeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolesList,
  delRoleRights,
  addRole,
  searchRole,
  setRole,
  delRole,
  getRightsList,
  allotRights
} from '../../api/rights'
export default {
  data () {
    return {
      rolesList: [],
      // 控制添加角色对话框
      addDialogVisible: false,
      // 添加角色对象
      addRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 控制修改角色的对话框
      setDialogVisible: false,
      // 修改角色信息
      setRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色的验证规则
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框
      allotDialogVisible: false,
      // 所有权限数据列表
      rightsList: [],
      // 绑定的tree树形控件的属性
      allotProps: {
        // 需要展示属性的值
        label: 'authName',
        children: 'children'
      },
      // 选中项id组成的数组
      defaultCheckedKeys: [],
      // 授权角色id
      roleId: 0
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await getRolesList()
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    async delRoleRights (role, rightsId) {
      const result = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(result)
      if (result === 'cancel') return this.$message.info('已取消删除')
      const { data: res } = await delRoleRights(role.id, rightsId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    addDialogClose () {
      this.$refs.addRuleFormRef.resetFields()
    },
    addRole () {
      this.$refs.addRuleFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await addRole(this.addRuleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
        this.addDialogVisible = false
      })
    },
    setDialogClose () {
      this.$refs.setRuleFormRef.resetFields()
    },
    async searchRole (id) {
      const { data: res } = await searchRole(id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.setRuleForm = res.data
      this.setDialogVisible = true
      console.log(res)
    },
    async setRole () {
      const { data: res } = await setRole(
        this.setRuleForm.roleId,
        this.setRuleForm
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setDialogVisible = false
    },
    async delRole (id) {
      const result = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(result)
      if (result === 'cancel') return this.$message.info('已取消删除')
      const { data: res } = await delRole(id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    async allotRoleRights (role) {
      const { data: res } = await getRightsList('tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.roleId = role.id
      this.getLeafId(role, this.defaultCheckedKeys)
      this.allotDialogVisible = true
    },
    allotClose () {
      this.defaultCheckedKeys = []
    },
    // 通过递归获取三级权限id，并保存到defaultCheckedKeys数组中
    getLeafId (node, arr) {
      // 通过判断是否有children属性，是不是三级节点，如果是三级节点，将此时的id存到我们arr中
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => { this.getLeafId(item, arr) })
    },
    // 选择权限，提交后台
    async allotRights () {
      const keys = [...this.$refs.allotTreeRef.getCheckedKeys(), ...this.$refs.allotTreeRef.getHalfCheckedKeys()]
      const rids = keys.join(',')
      const { data: res } = await allotRights(this.roleId, rids)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.allotDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.el-row {
  display: flex;
  align-items: center;
}
.bt {
  border-top: 1px solid #eee;
}
.bb {
  border-bottom: 1px solid #eee;
}
</style>
